<template>
  <PublicLoading v-if="loading.mounted" />
  <div v-else class="dt-main-tabs-content">
    <!-- <div class="dt-content-left">
      <PmChatList />
    </div> --><!--可选-->
    <div class="dt-content-main">
      <div class="dt-content-head">
        <div class="dt-content-head-tab">
          <div class="dt-head-title">
            <div class="dt-head-breadcrumb" @click="goBack">
              <i class="el-icon-arrow-left"></i>
              <span>返回</span>
              <em>|</em>
            </div>
            <span>编辑模板</span>
          </div>
        </div>
      </div>
      <div class="dt-content-page">
        <div class="dt-node-box">
          <el-form ref="templateNameValidateForm" :model="templateNameValidateForm" label-width="106px" label-position="left">
            <div class="dt-toolbar">
              <el-form-item label="节点模板" prop="templateName" :rules="[{ required: true, message: '请输入节点模板名称！' }]">
                <el-input
                  v-model.trim="templateNameValidateForm.templateName"
                  placeholder="请输入内容"
                  style="width: 400px"
                  autocomplete="off"
                  maxlength="20"
                ></el-input>
              </el-form-item>
              <!-- <div class="dt-template-button">
                <el-button icon="el-icon-goods">模板市场</el-button>
                <el-button icon="el-icon-takeaway-box">管理我的模板</el-button>
              </div> -->
            </div>
            <div class="dt-node-list">
              <PublicEmpty v-if="templateList.length == 0" :ishowImage="true" />
              <template v-else>
                <div class="dt-node-item por" :class="index > 0 ? 'dt-line' : ''" v-for="(item, index) in templateList" :key="item.id">
                  <el-popover placement="bottom" trigger="click" popper-class="dt-card-popover" v-model="item.isShowPopover">
                    <ul class="dt-add-node">
                      <li @click="openSetNode('1', index)">添加左侧节点</li>
                      <li @click="openSetNode('2', index)">添加右侧节点</li>
                    </ul>
                    <i slot="reference" class="dt-circle-plus poa"></i>
                  </el-popover>
                  <div class="dt-node-card por">
                    <div class="dt-nodeclose poa">
                      <i class="el-icon-close" @click.stop="openDetele(index, item)"></i>
                    </div>
                    <h4>{{ item.nodeName }}</h4>
                    <p class="dt-null"></p>
                    <div class="dt-node-progress">
                      <span>权重：{{ item.weight }}%</span>
                      <!-- <span>进度：{{item.progress?item.progress:0}}%</span> -->
                    </div>
                    <div class="dt-dashed-line poa"></div>
                  </div>
                  <div class="dt-node-time">
                    <!-- <p>共 {{item.planDays}} 天</p> -->
                    <el-button type="text" @click.stop="openEdit(item, index)">编辑</el-button>
                  </div>
                </div>
              </template>
            </div>
            <div class="dt-button-box">
              <el-button type="primary" size="medium" @click="submitFormTemplate('templateNameValidateForm')">保存</el-button>
              <el-button size=" medium" @click="resetFormTemplate('templateNameValidateForm')">取消</el-button>
            </div>
          </el-form>
        </div>
      </div>
    </div>
    <!-- 创建节点-->
    <el-dialog
      class="dt-set-node"
      :title="setNodeTitle"
      :visible.sync="setNodeIsShow"
      :append-to-body="true"
      width="680px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="closeCallback"
    >
      <el-form
        :model="setNodeRuleForm"
        :rules="setNodeRules"
        ref="setNodeRuleForm"
        label-width="100px"
        label-position="left"
        class="dt-create-pm-box"
      >
        <el-form-item label="节点名称" prop="nodeName">
          <el-input
            type="text"
            placeholder="请输入节点名称，最多8个字"
            v-model.trim="setNodeRuleForm.nodeName"
            maxlength="8"
            show-word-limit
            style="width: 540px"
          >
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="计划工期" prop="planDays">
          <el-input placeholder="输入天数" v-model.trim="setNodeRuleForm.planDays" style="width:160px" @input="planDaysInput">
            <template slot="append">天</template>
          </el-input>
        </el-form-item> -->
        <el-form-item label="权重占比" prop="weight">
          <el-input placeholder="权重占比" v-model.trim="setNodeRuleForm.weight" :maxlength="3" style="width: 160px" @input="weightInput">
            <template slot="append"> % </template>
          </el-input>
          <span v-if="residueWeight >= 0" class="dt-residue-weight">剩余可分配权重 {{ residueWeight }}%</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" type="primary" @click="submitFormSetNode('setNodeRuleForm')" :loading="loading.setNodeloading">确定</el-button>
        <el-button size="medium" @click="resetFormSetNode('setNodeRuleForm')">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      uid: this.$tools.getDecrypt(this.$store.state.uid), //用户id
      loading: { mounted: false },

      form: {
        template: '节点模板-1'
      },
      templateList: [],
      setNodeIsShow: false,
      nodeIndex: '',
      setNodeTitle: '设置节点',
      totalWeight: 0,
      initWeight: 0,
      residueWeight: 0,
      templateNameValidateForm: {
        templateName: ''
      },
      setNodeRuleForm: {
        isAdd: 0,
        nodeName: '',
        planDays: '',
        weight: ''
      },
      setNodeRules: {
        nodeName: [{ required: true, message: '请输入节点名称，最多8个字', trigger: 'blur' }],
        // planDays: [{ required: true, message: '请输入天数', trigger: 'blur' }],
        weight: [
          { required: true, message: '请输入权重占比', trigger: 'blur' },
          { validator: this.validateWeight, trigger: 'blur' }
        ]
      }
      // btnVisible: true
    }
  },
  computed: {
    query() {
      return this.$tools.getQuery(this)
    }
  },
  methods: {
    showCard() {
      this.dataCard.isShowCard = true
    },
    goBack() {
      this.$router.push('/main/#/pm?tab=mana-template&rootProjectId=' + this.query.rootProjectId)
    },
    validateWeight(rule, value, callback) {
      if (value <= 0) {
        callback(new Error('请输入大于0数字'))
      } else if (value > parseFloat(this.residueWeight)) {
        callback(new Error('不能超出剩余可分配权重'))
      } else {
        callback()
      }
    },
    weightInput(value) {
      // 只允许输入数字
      this.setNodeRuleForm.weight = value.replace(/[^\d]/g, '')
    },
    planDaysInput(value) {
      // 只允许输入数字
      this.setNodeRuleForm.planDays = value.replace(/[^\d]/g, '')
    },
    closeCallback() {
      this.setNodeIsShow = false
      this.setNodeRuleForm = {
        nodeName: '',
        planDays: '',
        weight: '',
        isAdd: 0
      }
      this.setNodeTitle = '设置节点'
    },
    openEdit(item, index) {
      this.nodeIndex = ''
      this.nodeIndex = index
      // console.log(item)
      this.setNodeTitle = '编辑节点'
      this.setNodeIsShow = true
      this.setNodeRuleForm.nodeName = item.nodeName
      this.setNodeRuleForm.planDays = item.planDays
      this.setNodeRuleForm.weight = item.weight + ''
      this.residueWeight = this.initWeight
      this.residueWeight = this.$tools.accAdd(this.residueWeight, item.weight)
    },
    openSetNode(type, index) {
      this.residueWeight = this.initWeight

      this.templateList[index].isShowPopover = false
      this.setNodeIsShow = true
      if (type == 1) {
        // 向左添加节点
        this.setNodeTitle = '添加左侧节点'
        // if (index == 0) {
        //   this.setNodeRuleForm.sonId = this.templateList[index].id
        // } else {
        //   this.setNodeRuleForm.parentId = this.templateList[index - 1].id
        //   this.setNodeRuleForm.sonId = this.templateList[index].id
        // }
        this.nodeIndex = index
        this.setNodeRuleForm.isAdd = 1
      } else if (type == 2) {
        // 向右添加节点
        this.setNodeTitle = '添加右侧节点'

        // if (index == this.templateList.length - 1) {
        //   this.setNodeRuleForm.parentId = this.templateList[index].id
        // } else {
        //   this.setNodeRuleForm.parentId = this.templateList[index].id
        //   this.setNodeRuleForm.sonId = this.templateList[index + 1].id
        // }
        this.nodeIndex = index + 1
        this.setNodeRuleForm.isAdd = 1
      }
    },
    editNode() {
      let item = { nodeName: this.setNodeRuleForm.nodeName, weight: this.setNodeRuleForm.weight }
      this.templateList.splice(this.nodeIndex, 1, item)
      // 计算剩余权重
      this.totalWeight = 0
      this.templateList.forEach((item) => {
        item.isShowPopover = false
        this.totalWeight = this.$tools.accAdd(this.totalWeight, item.weight)
      })
      this.initWeight = this.residueWeight = this.$tools.Subtr(100, this.totalWeight)
      this.closeCallback()
    },
    createNode() {
      let item = { nodeName: this.setNodeRuleForm.nodeName, weight: this.setNodeRuleForm.weight }
      this.templateList.splice(this.nodeIndex, 0, item)
      // 计算剩余权重
      this.totalWeight = 0
      this.templateList.forEach((item) => {
        item.isShowPopover = false
        this.totalWeight = this.$tools.accAdd(this.totalWeight, item.weight)
      })
      this.initWeight = this.residueWeight = this.$tools.Subtr(100, this.totalWeight)
      this.closeCallback()
    },
    openDetele(index, item) {
      this.$confirm('确定删除该该节点?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'dt-button-cancle is-plain',
        type: 'warning'
      })
        .then(() => {
          this.initWeight = this.residueWeight = this.$tools.accAdd(this.residueWeight, item.weight)
          this.templateList.splice(index, 1)
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // })
        })
    },
    submitFormSetNode(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.setNodeloading = true
          if (this.setNodeRuleForm.isAdd) {
            this.createNode()
          } else {
            this.editNode()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetFormSetNode(formName) {
      this.$refs[formName].resetFields()
      this.setNodeIsShow = false
    },
    getTreeData(data) {
      var items = [],
        deepEach = function (data) {
          var item = {}
          for (var key in data) {
            if (key !== 'children') {
              item[key] = data[key]
            } else {
              if (data['children'].length) {
                deepEach(data['children'][0])
              }
            }
          }
          items.push(item)
        }
      if (data) {
        deepEach(data)
      }
      return items.reverse()
    },
    getTemplateDetail() {
      var data = [
          {
            userId: this.uid,
            templateId: this.query.templateId
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/template/templateDetail'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.templateList = this.getTreeData(data.data.rootTemplateNode)

              this.totalWeight = 0
              this.templateList.forEach((item) => {
                item.isShowPopover = false
                this.totalWeight = this.$tools.accAdd(this.totalWeight, item.weight)
              })

              this.templateNameValidateForm.templateName = data.data.templateName
              this.initWeight = this.residueWeight = this.$tools.Subtr(100, this.totalWeight)
            } else {
              console.log(data.message)
            }
          })
        })
        .catch((error) => {})
    },
    submitTemplate() {
      var data = [
          {
            userId: this.uid,
            templateId: this.query.templateId,
            templateName: this.templateNameValidateForm.templateName,
            nodeJson: JSON.stringify(this.templateList),
            remark: ''
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/template/editTemplate'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.$message({
                message: '编辑模板成功',
                type: 'success',
                onClose: () => {
                  this.$router.push('/main/#/pm?tab=mana-template&rootProjectId' + this.query.rootProjectId)
                }
              })
            } else {
              console.log(data.message)
            }
          })
        })
        .catch((error) => {})
    },
    submitFormTemplate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.templateList.length == 0) {
            this.$message.error('暂无模板可以提交！')
          } else {
            this.submitTemplate()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetFormTemplate(formName) {
      // this.$refs[formName].resetFields()
      // this.btnVisible = false
      this.$confirm(`离开页面后，修改的数据将无法保存`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'dt-button-cancle is-plain',
        type: 'warning'
      })
        .then(() => {
          this.goBack()
        })
        .catch(() => {
          return
        })
    }
  },
  mounted() {
    if (this.query.templateId) {
      this.getTemplateDetail()
    }
    // window.onbeforeunload = function (e) {
    //   e = e || window.event
    //   // 兼容IE8和Firefox 4之前的版本
    //   if (e) {
    //     e.returnValue = '离开页面后，修改的数据将无法保存'
    //   }
    //   return '离开页面后，修改的数据将无法保存'
    // }
  }
  // beforeRouteUpdate(to, from, next) {
  //   if (!this.btnVisible) {
  //     this.$confirm(`系统可能不会保存您所做的更改，确定离开本页面吗？`, '提示', {
  //       confirmButtonText: '确定',
  //       cancelButtonText: '取消',
  // cancelButtonClass: 'dt-button-cancle is-plain',
  //       type: 'warning'
  //     })
  //       .then(() => {
  //         next()
  //       })
  //       .catch(() => {
  //         return
  //       })
  //   } else {
  //     next()
  //   }
  // },
  // beforeRouteLeave(to, from, next) {
  //   if (!this.btnVisible) {
  //     this.$confirm(`系统可能不会保存您所做的更改，确定离开本页面吗？`, '提示', {
  //       confirmButtonText: '确定',
  //       cancelButtonText: '取消',
  // cancelButtonClass: 'dt-button-cancle is-plain',
  //       type: 'warning'
  //     })
  //       .then(() => {
  //         next()
  //       })
  //       .catch(() => {
  //         return
  //       })
  //   } else {
  //     next()
  //   }
  // }
}
</script>
<style scoped>
.dt-content-page {
  background: #f2f3f5;
}
.dt-node-box {
  background: #fff;
}
.dt-toolbar {
  padding: 0px 14px;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  flex-direction: row;
  -webkit-align-items: flex-start;
  align-items: flex-start;

  justify-content: space-between;
  align-items: center;

  height: 69px;
  border-bottom: 1px solid #dcdfe6;
}
.dt-toolbar >>> .el-input__inner {
  height: 36px;
  line-height: 36px;
}

.el-form-item {
  margin-bottom: 0px;
}
.dt-node-list {
  padding: 14px;
  display: flex;
  display: -webkit-flex;
  -webkit-flex-direction: row;
  flex-direction: row;
  overflow-x: auto;
}
.dt-node-add,
.dt-node-card {
  display: -webkit-flex;
  display: flex;
  width: 200px;
  height: 92px;
  border: 1px dashed #dcdfe6;
  border-radius: 8px;

  justify-content: center;
  cursor: pointer;
}
.dt-node-add .el-button--text {
  color: #c0c4cc;
}
.dt-node-add:hover {
  border: 1px dashed #d6e4ff;
  background: #f0f5ff;
}
.dt-node-add:hover .el-button--text {
  color: #2f54eb;
}

.dt-node-item {
  /* margin-bottom: 14px; */
  width: 202px;
  display: flex;
  display: -webkit-flex;
  -webkit-flex-direction: column;
  flex-direction: column;
}
.dt-node-card {
  width: 178px;
  height: 63px;
  padding: 16px 12px 12px;
  border: 1px solid #d6e4ff;
  -webkit-flex-direction: column;
  flex-direction: column;
}
.dt-node-card:hover {
  background-color: #85a5ff;
}
.dt-node-card:hover h4,
.dt-node-card:hover p,
.dt-node-card:hover .dt-node-progress {
  color: #fff;
}
.dt-node-card h4 {
  color: #1f1f1f;
}
.dt-node-card p {
  margin: 17px 0px;
  color: #606266;
}
.dt-node-card >>> .el-popover {
  min-width: 125px;
}
.dt-node-progress {
  margin-top: 5px;
  display: -webkit-flex;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  font-size: 12px;
  color: #606266;
}

.dt-nodeclose {
  top: -1px;
  right: -1px;
  width: 20px;
  height: 20px;
  background: #f2f3f5;
  display: flex;
  display: -webkit-flex;
  justify-content: center;
  align-items: center;
  border-top-right-radius: 8px;
  border-bottom-left-radius: 8px;
}
.dt-circle-plus {
  top: 36px;
  right: -10px;
  z-index: 10;
  width: 20px;
  height: 20px;
  background: url(/skb/img/add_node.png) no-repeat center;
}
.dt-circle-plus:hover {
  background: url(/skb/img/add_node_hover.png) no-repeat center;
}
.dt-add-node {
  border-radius: 5px;
}
.dt-add-node li {
  padding: 0px 20px;
  line-height: 32px;
  cursor: pointer;
}
.dt-add-node li:hover {
  background-color: #f0f5ff;
}

.dt-node-time {
  margin-top: 8px;
  display: flex;
  display: -webkit-flex;
  font-size: 12px;
  color: #606266;
  justify-content: center;
  align-items: center;
}
.dt-node-time >>> .el-button {
  margin-left: 10px;
  padding: 0px;
  font-size: 12px;
}
.dt-line {
  margin-left: 60px;
}
.dt-line .dt-dashed-line {
  left: -63px;
  width: 62px;
  height: 1;
  border-top: 1px dashed #e1e6f0;
}
.dt-null {
  color: #909399;
}

.dt-button-box {
  padding: 14px;
  border-top: 1px solid #e0e0e0;
}

/* 设置节点弹窗 */
.dt-residue-weight {
  margin-left: 6px;
}

.dt-set-node >>> .el-dialog__header {
  padding-bottom: 0px;
}
.dt-set-node >>> .el-dialog__body {
  padding: 20px 20px 0px;
}
.dt-set-node >>> .el-input__inner,
.dt-template-box >>> .el-input__inner {
  height: 36px;
  line-height: 36px;
}
.dt-set-node >>> .el-form-item__label,
.dt-set-node >>> .el-form-item__content {
  line-height: 36px;
}
.dialog-footer .el-button--default {
  color: #1f1f1f;
}
.dialog-footer .el-button {
  padding: 10px 19px;
}
.el-button + .el-button {
  margin-left: 6px;
}

.dt-set-node >>> .el-input-group__append {
  padding: 0px;
  width: 40px;
  text-align: center;
}
.dt-set-node >>> .el-form-item {
  margin-bottom: 20px;
}
.dt-set-node >>> .el-dialog__footer {
  border-top: 1px solid #ecf0f8;
  padding: 15px 20px;
}
.dt-set-node >>> .el-dialog__footer {
  border-top: 1px solid #ecf0f8;
  padding: 15px 20px;
}
</style>
